#!/usr/bin/env bash

# Copyright 2014, Joyent Inc. All rights reserved
#
# This script sets the password for the root user if this:
#
#  "users": [{"name": "root"}] 
#
# has been set in the image manifest.
#
# This script must only be run once via firstboot. The script will first check 
# /etc/shadow to ensure a root password is not being overwritten.

# load common functions and vars
. /lib/smartdc/lib_smartdc_scripts.cfg

lib_smartdc_info "Start of $(basename $0) script"

# Check /etc/shadow. If root pass is set, exit so we don't clobber a users 
# already set password.
passset=$(cat /etc/shadow | grep root | awk -F':' '{print $2;}')
if [[ -n $passset ]]; then
  lib_smartdc_fatal "The root password already set in /etc/shadow. Extiting."
fi

# Check if root_pw is set in meta data
pass=$($MDATA_GET_BIN root_pw)
if [[ $? -eq 0 ]] ; then
    lib_smartdc_info "Setting root password to value of meta-data root_pw."
    echo "root:${pass}" | chpasswd
else
    lib_smartdc_info "No root password set in root_pw. Skipping."
fi
